package com.back.end.Controller.Web;

import com.back.end.Modal.Admin;
import com.back.end.Service.AdminService;
import com.back.end.enums.ResultCode;
import com.back.end.utils.token.JwtUtil;
import com.back.end.utils.redis.RedisUtil;
import com.back.end.vo.Result;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

@RestController
@RequestMapping("/admin")
@CrossOrigin
public class AdminController {

    @Resource
    private AdminService adminService;

    @Resource
    private RedisUtil redisUtil;
    Logger logger = LoggerFactory.getLogger(AdminController.class);

    @PostMapping("/login")
    public Result login(String username, String password) {
        logger.info(username + "用户登录");
        Admin admin = new Admin();
        admin.setUsername(username);
        admin.setPassword(password);
        if (adminService.find_admin(admin)) {
            logger.info(username + "用户验证成功");
            String userId = UUID.randomUUID().toString();
            Map<String, Object> info = new HashMap<>();
            info.put("username", username);
            info.put("password", password);
            String token = JwtUtil.sign(userId, info);
            redisUtil.set("token", token, 60 * 24 * 30);
            return Result.success(token);
        } else {
            logger.info(username + "验证失败");
            return Result.error(ResultCode.LOGIN_ERROR);
        }
    }

    @PostMapping("/restPassword")
    public Result requestRestPassword(String username, String password) {
        Admin admin = new Admin();
        admin.setUsername(username);
        admin.setPassword(password);
        adminService.rest_password(admin);
        return Result.success("更新成功");
    }

    @RequestMapping("/index")
    public Result test() {
        return Result.success("mess");
    }
}
